
#include "SpaceShooter.h"
#include "defs.h"

void SpaceShooter::loop(){

	std::vector<Object*>::iterator	i;
	std::vector<Animation>::iterator	animIt;
	std::vector<std::vector<Object*>::iterator> elementsToRemove;
	std::vector<std::vector<Animation>::iterator> animsToRemove;

	switch(gameState)
	{
		case INGAME:

			spaceBg.loop();

			//Objects
			for(int j = 0; j < objectList.size(); j++)
				objectList[j]->loop();

			//Animations
			for(int j = 0; j < animationList.size(); j++)
				animationList[j].loop();

			//Health Text
			char healthStr[14];
			sprintf_s(healthStr, "Health: %d", ((Ship*) getPlayerShip())->getShipHealth());
			healthText.setText(healthStr);

			//Remove objects out of screen (skip first because it's our ship)
			for(i = objectList.begin(); i != objectList.end(); i++)
				if( (*i)->getX() < 0 || (*i)->getX() > WND_WIDTH ||
				    (*i)->getY() < -1000 || (*i)->getY() > WND_HEIGHT )
						elementsToRemove.push_back(i);

			//Remove destroyed ship and adds explosion animation
			for(i = objectList.begin(); i != objectList.end(); i++)
				if( ((Ship*) *i)->getShipHealth() <= 0 )
				{
					elementsToRemove.push_back(i);

					explosionAnim.stop();
					explosionAnim.rewind();

					explosionAnim.setPos(((Ship*) *i)->getX(), ((Ship*) *i)->getY());

					explosionAnim.play();

					animationList.push_back(explosionAnim);
				}

			//Remove stopped animations
			for( animIt = animationList.begin(); animIt != animationList.end(); animIt++ )
				if(!animIt->isPlaying())
					animsToRemove.push_back(animIt);

			for(int j = 0; j < elementsToRemove.size(); j++)
				objectList.erase(elementsToRemove[j]);

			for(int j = 0; j < animsToRemove.size(); j++)
				animationList.erase(animsToRemove[j]);

			elementsToRemove.clear();
			animsToRemove.clear();
						
		break;

		default:
			return;
	}

	// -------------------------------------------------------

	FPS::fpsControl.OnLoop();

	sprintf_s(windowTitle, "SpaceShooter - FPS: %d", FPS::fpsControl.getFPS());
	SDL_WM_SetCaption(windowTitle, NULL);
}

